//
//  YFPayManager.m
//  project
//
//  Created by Winny Zhang on 2019/3/29.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFPayManager.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "YFMobManagerConst.h"
#import "UPPaymentControl.h"


// 提示信息
static NSString * const YFPaySuccessMessage = @"支付成功";
static NSString * const YFPayFailMessage = @"支付失败";
static NSString * const YFNotInstallWechat = @"您未安装微信";

@interface YFPayManager () <NSCopying, NSMutableCopying, WXApiDelegate>

/**
 微信支付完成回调
 */
@property (nonatomic, copy) YFWechatPayCompletion wechatPayCompletion;

/**
 支付宝完成回调
 */
@property (nonatomic, copy) YFAliPayCompletion aliPayCompletion;

/**
 银联支付完成回调
 */
@property (nonatomic, copy) YFUnionPayCompletion unionPayCompletion;

@end

@implementation YFPayManager

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 绝对单例
static YFPayManager *_manager = nil;
+ (instancetype)shared {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [[[self class] alloc] init];
        
        // 支付宝支付回调通知
        [[NSNotificationCenter defaultCenter] addObserver:_manager
                                                 selector:@selector(handleAliPayResult:)
                                                     name:NotificationAliPayResult
                                                   object:nil];
        // 银联支付回调通知
        [[NSNotificationCenter defaultCenter] addObserver:_manager
                                                 selector:@selector(handleUnionPayResult:)
                                                     name:NotificationUnionPayResult
                                                   object:nil];
    });
    return _manager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}

- (instancetype)copyWithZone:(NSZone *)zone {
    return _manager;
}

- (instancetype)mutableCopyWithZone:(NSZone *)zone {
    return _manager;
}

#pragma mark - 注册
/**
 注册支付宝、微信、银联
 */
+ (void)registerPlatforms {
    // 注册微信
    [WXApi registerApp:WechatAppId];
}

#pragma mark - 设置回调
/**
 微信支付设置回调

 @param url 要处理的 url
 */
+ (void)wechatHandleOpenWith:(NSURL *)url {
    [WXApi handleOpenURL:url delegate:[YFPayManager shared]];
}

/**
 支付宝支付设置回调

 @param url 要处理的 url
 @param callback 回调处理
 */
+ (void)aliPayprocessOrderWith:(NSURL *)url callback:(YFAliPayCompletion)callback {
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:callback];
    }
}

/**
 银联支付设置回调

 @param url 要处理的 url
 @param callback 回调处理
 */
+ (void)unionPayHandleOpenWith:(NSURL *)url callBack:(YFUnionPayCompletion)callback {
    if ([url.host isEqualToString:@"uppayresult"]) {
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:callback];
    }
}

#pragma mark - 微信支付
/**
 微信支付
 
 @param order 订单
 @param completion 完成回调
 */
+ (void)wechatPay:(YFWechatPayOrder *)order completion:(YFWechatPayCompletion)completion {
    [[YFPayManager shared] wechatPay:order completion:completion];
}

/**
 微信支付

 @param order 订单
 @param completion 完成回调
 */
- (void)wechatPay:(YFWechatPayOrder *)order completion:(YFWechatPayCompletion)completion {
    
    if (![WXApi isWXAppInstalled]) {
        completion(NO, YFNotInstallWechat);
        return;
    }
    PayReq *req = [[PayReq alloc] init];
    req.partnerId = order.partnerId;
    req.prepayId = order.prepayId;
    req.nonceStr = order.nonceStr;
    req.timeStamp = order.timeStamp;
    req.package = @"Sign=WXPay";
    req.sign = order.sign;
    [WXApi sendReq:req];
    if ([YFPayManager shared].wechatPayCompletion) [YFPayManager shared].wechatPayCompletion = nil;
    [YFPayManager shared].wechatPayCompletion = completion;
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    
    // 微信支付回调
    if ([resp isKindOfClass:[PayResp class]]) {
        BOOL isSuccess = NO;
        NSString *message = @"";
        PayResp *payResp = (PayResp *)resp;
        switch (payResp.errCode) {
            case WXSuccess:
            {
                isSuccess = YES;
                message = YFPaySuccessMessage;
            }
                break;
            case WXErrCodeCommon:
            case WXErrCodeSentFail:
            case WXErrCodeAuthDeny:
            case WXErrCodeUnsupport:
            default:
            {
                isSuccess = NO;
                message = YFPayFailMessage;
            }
                break;
        }
        [YFPayManager shared].wechatPayCompletion(isSuccess, message);
    }
}

#pragma mark - 支付宝支付
/**
 支付宝支付
 
 @param order 支付订单
 @param completion 支付结果回调
 */
+ (void)aliPay:(NSString *)order completion:(YFAliPayCompletion)completion {
    [[YFPayManager shared] aliPay:order completion:completion];
}
/**
 支付宝支付

 @param order 支付订单
 @param completion 支付结果回调
 */
- (void)aliPay:(NSString *)order completion:(YFAliPayCompletion)completion {
    // 保存回调 block，等通知到达，执行通知方法里执行 该block
    if([YFPayManager shared].aliPayCompletion) [YFPayManager shared].aliPayCompletion = nil;
    [YFPayManager shared].aliPayCompletion = completion;
    [[AlipaySDK defaultService] payOrder:order fromScheme:AppScheme callback:self.aliPayCompletion];
}

#pragma mark - 银联支付
/**
 银联支付
 
 @param order 交易流水号
 @param viewController 需要展示的 ViewController 用户内嵌收银台的展示
 @param completion 支付结果回调
 */
+ (void)unionPay:(NSString *)order viewController:(UIViewController *)viewController completion:(YFUnionPayCompletion)completion {
    [[YFPayManager shared] unionPay:order viewController:viewController completion:completion];
}

/**
 银联支付

 @param order 交易流水号
 @param viewController 需要展示的 ViewController 用户内嵌收银台的展示
 @param completion 支付结果回调
 */
- (void)unionPay:(NSString *)order viewController:(UIViewController *)viewController completion:(YFUnionPayCompletion)completion {
    if (order.length <= 0) {
        LKLog(@"银联支付：交易流水号不正确");
        return;
    }
#ifdef DEBUG
    NSString *mode = @"01";
#else
    NSString *mode = @"00";
#endif
    // 保存回调 block，等通知到达，通知方法里执行 该block
    if ([YFPayManager shared].unionPayCompletion) [YFPayManager shared].unionPayCompletion = nil;
    [YFPayManager shared].unionPayCompletion = completion;
    [[UPPaymentControl defaultControl] startPay:order fromScheme:AppScheme mode:mode viewController:viewController];
}


#pragma mark - 通知执行方法
/**
 处理支付宝回调方法

 @param info 支付结果
 */
- (void)handleAliPayResult:(NSNotification *)info {
    [YFPayManager shared].aliPayCompletion(info.userInfo);
}

/**
 处理银联回调方法

 @param info 支付结果
 */
- (void)handleUnionPayResult:(NSNotification *)info {
    NSString *code = info.userInfo[@"code"];
    NSDictionary *result = info.userInfo[@"data"];
    [YFPayManager shared].unionPayCompletion(code, result);
}

@end
